package com.gjy.disruptor.uuid.dec.netty;

import com.gjy.disruptor.uuid.dec.disruptor.UuidEventProducer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Netty HTTP服务器主类。
 *
 * @author gjy
 * @version 1.0
 * @since 2025-10-11 09:14:47
 */
public class HttpUuidServer {

    private static final Logger logger = LoggerFactory.getLogger(HttpUuidServer.class);

    private final int port;
    private final UuidEventProducer producer;

    public HttpUuidServer(int port) {
        this.port = port;
        this.producer = new UuidEventProducer();
    }

    public void run() throws InterruptedException {
        // 配置NIO线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(1); // 接收连接
        EventLoopGroup workerGroup = new NioEventLoopGroup(); // 处理连接的I/O

        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 1024)
                    .handler(new LoggingHandler(LogLevel.INFO))
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            // HTTP编解码器
                            p.addLast(new HttpServerCodec());
                            // 将HTTP消息聚合成FullHttpRequest/FullHttpResponse
                            p.addLast(new HttpObjectAggregator(1024 * 1024));
                            // 自定义的请求处理逻辑
                            p.addLast(new UuidRequestHandler(producer));
                        }
                    });

            // 绑定端口，开始接收连接
            ChannelFuture f = b.bind(port).sync();

            logger.info("UUID Server started, listening on port {}", port);

            // 等待服务器套接字关闭
            f.channel().closeFuture().sync();
        } finally {
            // 优雅地关闭线程组
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
            producer.shutdown();
            logger.info("UUID Server stopped.");
        }
    }

}
